package com.mashibing.cloudalibabaconsumernacos8083.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.mashibing.cloudalibabaconsumernacos8083.entity.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class DemoController {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 消费者去访问具体服务，这种写法可以实现
     * 配置文件和代码的分离
     */
    @Value("${service-url.nacos-user-service}")
    private String serverURL;


    @GetMapping(value = "consumer/nacos")
    public String getDiscovery(){
        System.err.println(serverURL);
        return restTemplate.getForObject(serverURL + "/mashibing", String.class);
    }

    @GetMapping("/consumer/fallback/{id}")
    //添加SentinelResource注解的fallback属性，同时设置方法来解决Java异常
    @SentinelResource(value = "fallback", fallback = "fallbackHandler", blockHandler = "blockHandler"
                    ,exceptionsToIgnore = {NullPointerException.class})

    public JsonResult<String> fallback(@PathVariable Long id) {
        if (id <= 3) {
            //通过Ribbon发起远程访问，访问9003/9004
            JsonResult<String> result =
                    restTemplate.getForObject(serverURL + "/info/" + id, JsonResult.class);
            log.info("result:{}", result.getData());
            return result;
        } else {
            throw new NullPointerException("没有对应的数据记录");
        }
    }

    //保证方法签名基本保持一致，但是要添加异常类型参数
    public JsonResult<String> fallbackHandler(Long id,Throwable e){
        JsonResult<String> result = new JsonResult<>(0L, 444, "NullPointerException异常");
        return result;
    }

    //处理Sentinel限流
    public JsonResult<String> blockHandler(Long id, BlockException e){
        JsonResult<String> result = new JsonResult<>(0L, 445, "BlockException限流");
        return result;
    }
}